#include <stdio.h>
#include <stdlib.h>
#include "crossLinkGraph.h"

CrossGraph *createCrossGraph(int n) {
	CrossGraph *graph = (CrossGraph *)malloc(sizeof(CrossGraph));
	graph->nodes = (CrossVertex *)malloc(sizeof(CrossVertex) * n);

	graph->numEdge = 0;
	graph->numVertex = n;

	return graph;
}

void releaseCrossGraph(CrossGraph *graph) {
	int num = 0;
	if (graph) {
		if (graph->nodes) {
			for (int i = 0; i < graph->numVertex; ++i) {
				ArcBox *box = graph->nodes[i].firstOut;
				ArcBox *tmp;
				while (box) {
					tmp = box;
					box = box->tailNext;
					free(tmp);
					++num;
				}
			}
		}
		printf("release %d edge!\n", num);
		free(graph->nodes);
	}
	free(graph);
}

void initCrossGraph(CrossGraph *graph, int num, char *names[]) {
	for (int i = 0; i < num; ++i) {
		graph->nodes[i].no = i;
		graph->nodes[i].show = names[i];
		graph->nodes[i].firstIn = graph->nodes[i].firstOut = NULL;
	}
}

void addCrossArc(CrossGraph *graph, int tail, int head, int weight) {
	// 1. 先创建新节点
	ArcBox *box = malloc(sizeof(ArcBox));
	box->weight = weight;
	// 2. 处理这条边的关系，出和入的上一个节点  采用头插法
	// 2.1 出度
	box->tailVertex = tail;
	box->tailNext = graph->nodes[tail].firstOut;
	graph->nodes[tail].firstOut = box;
	// 2.2 入度
	box->headVertex = head;
	box->headNext = graph->nodes[head].firstIn;
	graph->nodes[head].firstIn = box;
}

// 统计firstIn对应的链表
int inDegreeCrossGraph(CrossGraph *graph, int no) {
	int count = 0;
	ArcBox *box = graph->nodes[no].firstIn;
	while (box) {
		++count;
		box = box->headNext;
	}
	return count;
}

int outDegreeCrossGraph(CrossGraph *graph, int no) {
	int count = 0;
	ArcBox *box = graph->nodes[no].firstOut;
	while (box) {
		++count;
		box = box->tailNext;
	}
	return count;
}
